Constructors in C# .Net

Ratings:
(4)
Views: 356
Banner-Img
Share this blog:

 

Constructors

A constructor is a special type of method, will be executed automatically while an object is about to create. De Constructors is a special type of method, will be executed automatically while an object is about to destroy. Constructors name must be the same as a class name without “RETURN TYPE”

Syntax

Public CL_Name () {   }

De Constructor name must be the same as a class name without a field  ( ~) Prefix and without return type and access specifier.

Syntax  

CL_ Name () { } Constructors are over loadable.

De -Constructors are not overloadable. Generally, constructors will be used to initialize the fields, to open connections or Files, etc.. Generally, deconstructors will be used to De Allocate the memory and to close the connections and files, etc. 

 These core tutorials will help you to learn the fundamentals of .NET. For an in-depth understanding and practical experience, explore Online ".NET Training".

Example on Constructors

Open windows form Application Project à Place a button à Code in GD

 

Class Test

{

Public Test ()

//Constructor

{

Message Box. Show (“From  Constructor ”);

}

~ Test ()

// De- Constructor

{

Message Box. Show  (“From  De -Constructor”)

}

  }

/Test  

Code for Button 1_click

{

Test t1 = new Test ();

Test t2 = new Test ();

Test t3 = new Test ();

}

  Execute the project

  Observations

When the above project is executed, then 3 times the constructor and 3 times de-constructor will be executed. After a project is terminated (closed), then within 2 sec Garbage collector will be loaded into the memory. Garbage collector Reclaims (clears), the memory allocated for the current project. The garbage collector can be invoked programmatically also with the help of GC. Collect ()    

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox